package org.baicaixiaozhan.learncommon.util;

import com.google.common.base.Preconditions;

/**
 * IP 工具集
 *
 * @since 2021/6/30
 * @author baicaixiaozhan
 */
public final class IPUtils {

    private static final String REGX_IP = "((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
    private static final String REGX_IPB = REGX_IP + "\\-" + REGX_IP;

    private IPUtils() {
        throw new AssertionError();
    }

    /**
     * 判断目标 IP 是否在指定 IP 段内
     *
     * @param targetIP 示例：192.168.1.255
     * @param IPRange 示例：192.168.1.120-192.168.1.254
     * @return boolean
     */
    public static boolean isIpWithinRange(String targetIP, String IPRange) {
        Preconditions.checkNotNull(IPRange, "IP段不能为空");
        Preconditions.checkNotNull(targetIP, "IP不能为空");

        IPRange = IPRange.trim();
        targetIP = targetIP.trim();

        if (!IPRange.matches(REGX_IPB) || !targetIP.matches(REGX_IP)) {
            return false;
        }
        int idx = IPRange.indexOf('-');
        String[] sips = IPRange.substring(0, idx).split("\\.");
        String[] sipe = IPRange.substring(idx + 1).split("\\.");
        String[] sipt = targetIP.split("\\.");
        long ips = 0L, ipe = 0L, ipt = 0L;
        for (int i = 0; i < 4; ++i) {
            ips = ips << 8 | Integer.parseInt(sips[i]);
            ipe = ipe << 8 | Integer.parseInt(sipe[i]);
            ipt = ipt << 8 | Integer.parseInt(sipt[i]);
        }
        if (ips > ipe) {
            long t = ips;
            ips = ipe;
            ipe = t;
        }
        return ips <= ipt && ipt <= ipe;
    }
}
